if(typeof mg == 'undefined') {
    var mg = {};
}

mg.initShareBtn = function()
{
    $('.share-btn').hover( function () {
        $('.share-icon-list').toggle();
    });
};

mg.initUserMenu = function(){
    $('.setting-account').mouseover( function () {
		$('.setting-list').show();
	});
	$('.setting-account').mouseout( function () {
		$('.setting-list').hide();
	});
};

if(typeof mg.homeTopBanner == 'undefined'){
    mg.homeTopBanner = {};
}

mg.homeTopBanner.bindEvent = function(carousel)
{
    $('#homeTopBannerController a').click(function(){
        var page = $(this).attr('data-page'); 
        carousel.scroll(page * 3 + 1);
        carousel.startAuto(2);
        mg.homeTopBanner.changeControllerStatus(page);
    });
};

mg.homeTopBanner.changeControllerStatus = function(page)
{
    $('#homeTopBannerController li').removeClass('current');
    $('#homeTopBannerController' + page).addClass('current');
};

mg.homeTopBanner.itemLastInCallback = function(carousel, item, idx, state)
{
    mg.homeTopBanner.changeControllerStatus(Math.ceil(idx / 3) - 1);
};

mg.homeTopBanner.init = function()
{
    jQuery('#homeTopBanner').jcarousel({
        auto: 2,
        wrap: 'last',
        visible: 3,
        initCallback: mg.homeTopBanner.bindEvent,
        itemLastInCallback:   mg.homeTopBanner.itemLastInCallback,
    });    
};

/*-------------- Leader board ---------------- */
if(typeof mg.leaderboard == 'undefined'){
    mg.leaderboard = {};
}
mg.leaderboard.load = function(parentId, osId)
{
    $.ajax({
        url: '/mg/index/leader-board',
        data: {parentId: parentId, os: osId},
        type: 'GET',
        success: function(data){
            $('#leaderBoardContainer').html(data);
        }
    });
};

/*-------------- Down load app ---------------- */
if(typeof mg.download == 'undefined'){
    mg.download = {};
}
$('.Download').live('click', function (){
    var pvId = $(this).attr('id');
    if(pvId == null || pvId < 0){
        return false;
    }
    mg.download.checkDownload(pvId);
    return false;
}); 

mg.download.saveLocalStorage = function(key, productInfo)
{
    var localData = JSON.parse(localStorage.getItem(key));
    if(!(localData instanceof Array)){
        localData = [];
    }
    for (var i = localData.length - 1; i >= 0; i--){
        if(localData[i]['productId'] == productInfo['productId']){
            localData.splice(i, 1);
        }
    }
    localData.unshift(productInfo);
    localStorage.setItem(key, JSON.stringify(localData));
};

mg.download.saveCookie = function(key, productInfo, exdays){
	var localData = mg.download.getCookie(key);
    if(localData == null){
        localData = [];
    }else{
    	localData = eval(localData);
    }
    
    for (var i = localData.length - 1; i >= 0; i--){
        if(localData[i]['productId'] == productInfo['productId']){
            localData.splice(i, 1);
        }
    }
    if(localData.length < 10){
	    localData.unshift(productInfo);
	    var value = JSON.stringify(localData);
		var exdate=new Date();
		exdate.setDate(exdate.getDate() + exdays);
		var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
		document.cookie=key + "=" + c_value;
    }
};
mg.download.getCookie = function (c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++){
	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x==c_name){ return unescape(y);}
	}
};
mg.download.checkDownload = function(pvId){
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/mg/download/check",
        data: { version_id : parseInt(pvId)},
        success: function(res) {
            if(res.status == 1){

            }else if(res.status == 2){
                if(res.saveLocalStorage == 1){
                    mg.download.saveCookie(res.localStorageKey, res.productInfo, 365);
                }
                
                if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
                    window.location.href= "itms-services://?action=download-manifest&url=http://staging.choapp.vn/mg/Downloadipa/xml/pvid/" + pvId ;
                } else {
                    window.location.href= "/mg/download/downloadfile/source/"+res.source;
                }
                
                return false;
            }else if(res.status == 3){
                mg.login.showPopup(mg.download.checkDownload, pvId);
            }else{
                mg.message.show(JSON.parse(res.error));
            }
        },
        complete: function(res) {
            
        }
    });
};

/* --------------------- message ----------------------*/
if(typeof mg.message == 'undefined'){
    mg.message = {};
}

mg.message.show = function(message, okCallback, cancelCallback)
{
    var html = '<div id="popupMessage" class="pop-up-box-2"><div class="pu-header"><div class="logo-min"></div><!--end .logo-min--><span class="app-title-3">Thông báo</span><a href="javascript:void(0);" class="close-btn" onclick="mg.message.cancelClick();">Đóng</a><!--end .close-btn--><div class="clear"></div></div><!--end .pu-header--><div class="pu-body"><p class="center p20t p10l p10r">' + message + '</p><div style="width:105px; margin:10px auto 0 auto"><a href="javascript:void(0);" class="ok-btn" onclick="mg.message.okClick();">Đồng ý</a><div class="clear"></div></div></div><!--end .pu-body--></div>';
    var overlay = '<div id="overlay" class="bg-overlay"></div>';
    $('body').append(html + overlay);
    
    if(typeof okCallback == 'function'){
        mg.message.okCallback = okCallbackk;
    } else {
        mg.message.okCallback = null;
    }
    
    if(typeof cancelCallback == 'function'){
        mg.message.cancelCallback = cancelCallback;
    } else {
        mg.message.cancelCallback = null;
    }
    $('#popupMessage').css('left', ((window.innerWidth - 438) / 2) + 'px');
};

mg.message.close = function()
{
    $('#popupMessage').remove();
    $('#overlay').remove();
};

mg.message.okClick = function()
{
    if(typeof mg.message.okCallback == 'function'){
        mg.message.okCallback();
    }
    mg.message.close();
};

mg.message.cancelClick = function()
{
    if(typeof mg.message.cancelCallback == 'function'){
        mg.message.cancelCallback();
    }
    mg.message.close();
};

/* ------------------ login ----------------------------- */
if(typeof mg.login == 'undefined'){
    mg.login = {};
}

mg.login.showPopup = function(callback, data)
{
    if($('#popupLogin').length == 0){
        $('body').append('<iframe id="popupLogin" src="' + window.location.protocol + '//' + window.location.host + '/dang-nhap" class="form-iframe" style="height: 266px;"></iframe><div id="overlay" class="bg-overlay"></div>');
    } else {
        $('#popupLogin').show();
        $('#overlay').remove();
    }
    $('#popupLogin').css('left', ((window.innerWidth - 438) / 2) + 'px');
    if(typeof callback == 'function'){
        mg.login.callback = callback;
        mg.login.callbackData = data;
    } else {
        mg.login.callback = null;
        mg.login.callbackData = null;
    }
};

mg.login.closePopup = function()
{
    $('#popupLogin').remove();
    $('#overlay').remove();
};

mg.login.loginSuccessCallBack = function()
{
    mg.login.closePopup();
    mg.login.checklogin();
};

mg.login.showUserInfo = function(profileName, avatar)
{
	var historyUrl = $('#historyUrl').val();
	var html = "";
	html += '<div class="user-field"><p class="user-name ellipsis-for-all">' + profileName + '</p>';
	html += '<div class="setting-account"><a href="#" class="setting-btn">Chỉnh</a><ul class="setting-list">';
	html += '<li><a href="' + historyUrl + '" target="_blank">Ứng dụng đã tải</a></li>';
	html += '<li><a href="http://sso2.zing.vn/?method=logout&return=' + window.location + '">Thoát</a></li>';
	html += '</ul></div>';
    $('#userInfo').html(html);
    mg.initUserMenu();
};
mg.login.checklogin = function() {
    $.ajax({
        url: 'http://mapi.zing.vn/checklogin.php',
        dataType: 'jsonp',        
        success: function(data) {
            if (data.a_ban_id != '') {
                            setCookie('v_a_ban_id', data.a_ban_id, '', '/', '.choapp.vn', '');
                            setCookie('v_a_event_id', data.a_event_id, '', '/', '.choapp.vn', '');
                            setCookie('v_a_p_id', data.a_p_id, '', '/', '.choapp.vn', '');
                            setCookie('v_a_type_id', data.a_type_id, '', '/', '.choapp.vn', '');
                            
                }
            if(data.isLogin && data.acn != '' && data.vngauth != '')
            {
                $.post("/mg/auth/confirm", { sid:data.vngauth, acc: data.acn }, function(rs){
                    if (rs.result == 1) {
                        $.ajax({
                            url: 'http://union.zing.vn/gamecenter/index/get-user-info',
                            dataType: 'jsonp',
                            success: function(data){
                                if(data.result == 1) {
                                    mg.login.showUserInfo(data.profileName, data.avatar);
                                }
                            }
                        });   
                        if(typeof mg.login.callback == 'function'){
                            mg.login.callback(mg.login.callbackData);
                        }
                    }
                },'json');
            } else {
                $.get('/mg/auth/unset-session');
            }
        }
    });
};

/* ----------------------- register ------------------- */
if(typeof mg.register == 'undefined'){
    mg.register = {};
}

mg.register.showPopup = function()
{
    if($('#popupRegister').length == 0){
        $('body').append('<div id="popupRegister" class="form-iframe" style="width: 430px; height: 445px;" ><iframe src="https://id.zing.vn/quickregister/game/index.111.1.2.3.html" style="height: 100%; width: 100%; border: 0px;"></iframe><a href="javascript:void(0);" onclick="mg.register.closePopup();" class="BtCloseReg" title="Đóng">Đóng</a></div><div id="overlay" class="bg-overlay"></div>');
    } else {
        $('#popupRegister').show();
        $('#overlay').remove();
    }
    $('#popupRegister').css('left', ((window.innerWidth - 438) / 2) + 'px');
    return false;
};

mg.register.closePopup = function()
{
    $('#popupRegister').remove();
    $('#overlay').remove();
};

/* --------------- cookie ----------------------*/
function setCookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
     * if the expires variable is set, make the correct expires time, the
     * current script below will set it for x number of days, to make it for
     * hours, delete * 24, for minutes, delete * 60 * 24
     */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value)
            + ((expires) ? ";expires=" + expires_date.toGMTString() : "")
            + ((path) ? ";path=" + path : "")
            + ((domain) ? ";domain=" + domain : "")
            + ((secure) ? ";secure" : "");
}

if(typeof mg.search == 'undefined'){
    mg.search = {};
}

mg.search.init = function(){
	$("form#search").submit(function() {
		//var key = $("#textSearch").val().toLowerCase();
		//$("#textSearch").val(key);
		if($.trim($("#textSearch").val()) == ""){
			mg.message.show("Vui lòng nhập từ khóa để tìm kiếm !");
			return false;
		}else{
			var key = $("#textSearch").val().toLowerCase();
			key = key.replace(/(<([^>]+)>)/ig,"");
			$("#textSearch").val(key);
		}
	});
	
	$( "#textSearch" ).autocomplete({
		source: []
	});	
	var txtSearchEl =  $( "#textSearch" );
	var txtSearchCurrentValue = txtSearchEl.val();
	txtSearchEl.keyup(function(e) {
		if(this.disabled){ return; }
		switch (e.keyCode) {
			case 38: //KEY_UP:
			case 40: //KEY_DOWN:
			  return;
		}
		if (txtSearchCurrentValue !== txtSearchEl.val()) {
			$.ajax({  
				type: "POST",
				dataType: 'json', 
				url: "/mg/search/search-autocomplete", 
				// you can use an object here
				data: { key: $( "#textSearch" ).val(), osId: $( "#search-os" ).val() }, 
				success: function(res) {  			
					if(res != null && res.length > 0){
						$( "#textSearch" ).autocomplete({
							source: res
						});	
					}			
				},
				complete :function(res) {
				}	
			});	
		}
	});
	
	if($('#textSearch2').length > 0){
		$("form#pageSearch").submit(function() {
			//var key = $("#textSearch").val().toLowerCase();
			//$("#textSearch").val(key);
			if($.trim($("#textSearch2").val()) == ""){
				mg.message.show("Vui lòng nhập từ khóa để tìm kiếm !");
				return false;
			}else{
				var key = $("#textSearch2").val().toLowerCase();
				key = key.replace(/(<([^>]+)>)/ig,"");
				$("#textSearch2").val(key);
			}
		});		
		$( "#textSearch2" ).autocomplete({
			source: []
		});	
		var txtSearch2El =  $( "#textSearch2" );
		var txtSearch2CurrentValue = txtSearch2El.val();
		txtSearch2El.keyup(function(e) {
			if(this.disabled){ return; }
			switch (e.keyCode) {
				case 38: //KEY_UP:
				case 40: //KEY_DOWN:
				  return;
			}
			if (txtSearch2CurrentValue !== txtSearch2El.val()) {
				$.ajax({  
					type: "POST",
					dataType: 'json', 
					url: "/mg/search/search-autocomplete", 
					// you can use an object here
					data: { key: $( "#textSearch2" ).val(), osId: $( "#search-os" ).val() }, 
					success: function(res) {  			
						if(res != null && res.length > 0){
							$( "#textSearch2" ).autocomplete({
								source: res
							});	
						}			
					},
					complete :function(res) {
					}	
				});	
			}
		});		
	}
};

var closeDownloadPopup = function()
{
    $('#downloadPopup').remove();
    $('#overlay').remove();
};


/* ------------------ feedback ----------------------------- */
if(typeof mg.feedback == 'undefined'){
    mg.feedback = {};
}

mg.feedback.showPopup = function(callback, data)
{
    if($('#popupFeedback').length == 0){
        $('body').append('<iframe id="popupFeedback" src="' + window.location.protocol + '//' + window.location.host + '/gop-y?returnUrl=' + encodeURIComponent(window.location) + '" class="form-iframe" style="height: 460px;"></iframe><div id="overlay" class="bg-overlay"></div>');
    } else {
        $('#popupFeedback').show();
        $('#overlay').remove();
    }
    $('#popupFeedback').css('left', ((window.innerWidth - 438) / 2) + 'px');
    if(typeof callback == 'function'){
        mg.feedback.callback = callback;
        mg.feedback.callbackData = data;
    } else {
        mg.feedback.callback = null;
        mg.feedback.callbackData = null;
    }
};

mg.feedback.closePopup = function()
{
    $('#popupFeedback').remove();
    $('#overlay').remove();
};

mg.feedback.successCallBack = function()
{
	mg.feedback.closePopup();
	mg.message.show('Cám ơn bạn đã góp ý !');
};

$(document).ready(function(){
    mg.initShareBtn();
    mg.homeTopBanner.init();
    mg.login.checklogin();
    try {
        $('.lazy').lazyload();
    } catch(ex){
        
    }
    mg.search.init();
    $('#downloadPopup').css('left', ((window.innerWidth - 458) / 2) + 'px');
});